using System;
using System.Collections;
using System.Collections.Generic;
using System.Collections.Specialized;
using System.Linq;
using System.Text;
using System.Windows;
using System.Windows.Controls;

using Microsoft.Practices.Composite.Presentation.Regions;
using Microsoft.Practices.Composite.Regions;

namespace DanielVaughan.Calcium.Modularity.RegionAdapters
{
	class PanelRegionAdapter : RegionAdapterBase<Panel>
	{
		public PanelRegionAdapter(IRegionBehaviorFactory regionBehaviorFactory)
			: base(regionBehaviorFactory)
		{
			/* Intentionally left blank. */
		}

		protected override void Adapt(IRegion region, Panel regionTarget)
		{
			AddItems(regionTarget, region.ActiveViews.ToList());

			region.ActiveViews.CollectionChanged 
				+= delegate(object sender, NotifyCollectionChangedEventArgs e)
					{
						if (e.Action == NotifyCollectionChangedAction.Add)
						{
							AddItems(regionTarget, e.NewItems);
						}
						if (e.Action == NotifyCollectionChangedAction.Remove)
						{
							RemoveItems(regionTarget, e.OldItems);
						}
					};
		}

		protected override IRegion CreateRegion()
		{
			IRegion region = new AllActiveRegion();
			return region;
		}

		static void AddItems(Panel control, IList newItems)
		{
			ArgumentValidator.AssertNotNull(control, "control");

			if (newItems == null)
			{
				return;
			}

			foreach (var item in newItems.OfType<UIElement>())
			{
				control.Children.Add(item);
			}

			var dependencyItem = control as DependencyObject;
			if (dependencyItem == null)
			{
				return;
			}
			RegionManager.SetRegionName(dependencyItem, RegionManager.GetRegionName(dependencyItem));
		}

		static void RemoveItems(Panel control, IList oldItems)
		{
			if (oldItems == null)
			{
				return;
			}

			foreach (var item in oldItems.OfType<UIElement>())
			{
				control.Children.Remove(item);
			}
		}
	}
}
